#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

#define IP_ADDRESS_LENGTH 16

void packet_handler(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet) {
    struct ip *ip_header = (struct ip *)(packet + 14);  // Assuming Ethernet frame

    char source_ip[IP_ADDRESS_LENGTH];
    inet_ntop(AF_INET, &(ip_header->ip_src), source_ip, INET_ADDRSTRLEN);

    printf("Source IP: %s\n", source_ip);
}

int main() {
    pcap_t *handle;
    char errbuf[PCAP_ERRBUF_SIZE];

    // 打开数据包文件
    handle = pcap_open_offline("packet1.txt", errbuf);
    if (handle == NULL) {
        fprintf(stderr, "Error opening file: %s\n", errbuf);
        return 1;
    }

    // 读取并处理数据包
    if (pcap_loop(handle, 0, packet_handler, NULL) < 0) {
        fprintf(stderr, "Error in pcap_loop\n");
        return 1;
    }

    // 关闭文件
    pcap_close(handle);

    return 0;
}
